package org.outlook.xnotepad.command.action;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.outlook.xnotepad.command.action.CommandAction;
import org.outlook.xnotepad.command.action.SimpleCommandAction;

/**
 * function:
 * @author watson  email: watson.wu@hotmail.com
 * @date 2009-12-22
 */
public class Comman {
	private static final String TAP_SPACE = "$\t";
	private static final String WRAP_LINE = "$\n";
	private String wholeText;
	private String cmdText;
	private CommandAction cmdAct;
	private Pattern pattern = Pattern.compile("/exec:([^/]+?)/");
	private final String THIS = "$this";

	public Comman(String text) throws Exception {
		this.wholeText = text;
		Matcher matcher = pattern.matcher(wholeText);
		if(matcher.find()) {
			cmdText = matcher.group(1);
		} else
			throw new Exception("regex not format");

		parser(cmdText);
	}

	private void parser(String text) throws Exception {
		if(null != text && !"".equals(text)) {
			if(text.matches(".*\\[\\w*?-\\w*?\\](?:\\{\\w\\}){0,1}.*"))
				cmdAct = new SimpleCommandAction(text);
			else if(text.matches(".*%sysdate%\\[.+\\].*")) {
				cmdAct = new TimeStampCommandAction(text);
			}
		}
	}

	public String getResult(int index) {
		return wholeText.replace("/exec:"+cmdText+"/", cmdAct.getValue(index));
	}

	public String getResult(int index, String text) {
		if(cmdText.contains(THIS) && !cmdText.contains("\\$this")) {
			if(cmdText.matches("[^\\\\]+?\\$this\\(\\?U\\)"))
				cmdText = cmdText.replaceAll("\\$this\\(\\?U\\)", text.toUpperCase());
			else if (cmdText.matches("[^\\\\]+?\\$this\\(\\?L\\)"))
				cmdText = cmdText.replaceAll("\\$this\\(\\?L\\)", text.toLowerCase());
			else
				cmdText = cmdText.replaceAll(THIS, text);
		}
		if(cmdText.contains(WRAP_LINE) && !cmdText.contains("\\$\n")) {
			cmdText = cmdText.replaceAll(WRAP_LINE, '\n'+"");
		}
		if(cmdText.contains(TAP_SPACE) && !cmdText.contains("\\$\t")) {
			cmdText = cmdText.replaceAll(TAP_SPACE, '\t'+"");
		}
		return getResult(index);
	}

}